//
//  RetryAPI.m
//  Hq100yyApp
//
//  Created by ouyongyong on 2016/11/10.
//  Copyright © 2016年 edu24ol. All rights reserved.
//

#import "RetryAPI.h"
#import "DNSHelper.h"
#import "ReactiveCocoa/RACEXTScope.h"
#import "YTKNetworkConfig.h"
#import "DNSHelperSetting.h"

@interface RetryAPI ()

@property (nonatomic, copy)     NSString* requestUrl;
@property (nonatomic, copy)     NSString* requestBaseUrl;
@property (nonatomic, copy)     NSString *cdnUrl;
@property (nonatomic, assign)   YTKRequestMethod requestMethod;
@property (nonatomic, strong)   id requestArgument;
@property (nonatomic, assign)   NSInteger cacheTimeInSeconds;
@property (nonatomic, strong)   id jsonValidator;
//@property (nonatomic, copy)     AFConstructingBlock constructingBodyBlock;
@property (nonatomic, strong)   NSDictionary *requestHeaderFieldValueDictionary;

/** retryed iplist */
@property (nonatomic, strong) NSMutableArray *retryedIpArray;

@end

@implementation RetryAPI

- (instancetype)initWithRequest:(YTKRequest *)request
{
    if (self = [super init]) {
        _retryedIpArray = @[].mutableCopy;
        _requestUrl = [request requestUrl];
        _requestBaseUrl = [request baseUrl];
        _requestMethod = [request requestMethod];
        _requestArgument = [request requestArgument];
        _cacheTimeInSeconds = [request cacheTimeInSeconds];
        _jsonValidator = [request jsonValidator];
        
        self.constructingBodyBlock = [request constructingBodyBlock];
//        _constructingBodyBlock = [request constructingBodyBlock];//old
        _requestHeaderFieldValueDictionary = [request requestHeaderFieldValueDictionary];
        
        if ([request isKindOfClass:[self class]]) {
            _retryTime = ((RetryAPI *)request).retryTime + 1;
            _originHost = ((RetryAPI *)request).originHost;
            if (((RetryAPI *)request).retryedIpArray.count > 0) {
                [_retryedIpArray addObjectsFromArray:((RetryAPI *)request).retryedIpArray];
            }
            
        } else {
            _originHost = [[DNSHelper shareInstance] hostForRequest:request];
        }
        
    }
    return self;
}

- (BOOL)useCDN
{
    return YES;
}

- (BOOL)isRetryedForIp:(NSString *)ip
{
    if ([self.retryedIpArray containsObject:ip]) {
        return YES;
    }
    return NO;
}


- (void)startReqWithIp:(NSString *)newIp
{
    _tryIp = newIp;
    if ([self.retryedIpArray containsObject:_tryIp]) {
        DDLogInfo(@"RetryAPI - ip:%@ 重试过(%d)次,return\n",_tryIp,self.retryTime);
        self.failBlock(self);
        return;
    } else {
        [self.retryedIpArray addObject:_tryIp];
    }
    
    [self buildHeader];
    [self buildIpRequest];
    DDLogInfo(@"<RetryAPI> retry %@ for %d次", self.requestUrl, self.retryTime);
    @weakify(self);
    [self startWithCompletionBlockWithSuccess:self.succBlock failure:^(__kindof YTKBaseRequest *request) {
        @strongify(self);
        DDLogInfo(@"<RetryAPI> retry fail block %@ for %d次;error=%@\n", self.requestUrl, self.retryTime,request.error);
        [[DNSHelper shareInstance] handleFailRequest:request withSuccess:self.succBlock failure:self.failBlock];
    }];
    
    
    
}

- (void)buildHeader
{
    NSMutableDictionary *mHeader = self.requestHeaderFieldValueDictionary.mutableCopy;
    if (!mHeader) {
        mHeader = @{}.mutableCopy;
    }
    if (self.originHost) {
         [mHeader setObject:self.originHost forKey:@"Host"];
    }
    
    //    if (self.retryTime == 0) {
    //        return;
    //    }
    
    self.requestHeaderFieldValueDictionary = mHeader;
}

- (void)buildIpRequest
{
    NSString * httpPre = @"http";
    NSString * httpsPre = @"https";
    if ([self.requestUrl hasPrefix:httpPre]) {
        NSString *detailUrl = self.requestUrl;
        NSString *ip = self.tryIp;
        if (!ip) {
             return;
        }
        @try {
            NSURL *url = [NSURL URLWithString:detailUrl];
            detailUrl = [detailUrl stringByReplacingOccurrencesOfString:url.host withString:ip];
            if ([url.scheme hasPrefix:httpsPre]) {
                detailUrl = [detailUrl stringByReplacingOccurrencesOfString:url.scheme withString:httpPre];
            }
            
        } @catch (NSException *exception) {
            DDLogError(@"<RetryAPI> catch exp %@", exception);
        } @finally {
            self.requestUrl = detailUrl;
        }
        return;
    }
    
    NSString *baseUrl = [YTKNetworkConfig sharedConfig].baseUrl;
    if (self.requestBaseUrl.length) {
        baseUrl = self.requestBaseUrl;
    }
    NSAssert(baseUrl, @"base url cannot be nil");
    NSURL *url = [NSURL URLWithString:baseUrl];
    if (!url) {
         return;
    }
    NSString *host = url.host;
    if (!host) {
         return;
    }
    NSString *ip = self.tryIp;
    @try {
        baseUrl = [baseUrl stringByReplacingOccurrencesOfString:host withString:ip];
        if ([url.scheme hasPrefix:httpsPre]) {
            baseUrl = [baseUrl stringByReplacingOccurrencesOfString:url.scheme withString:httpPre];
        }
    } @catch (NSException *exception) {
        DDLogError(@"<RetryAPI> catch exp %@", exception);
    } @finally {
        self.cdnUrl = baseUrl;
    }
}

- (void)dealloc
{
    DDLogDebug(@"<RetryAPI> dealloc(%@)", self.originHost);
}
@end


